package uni.UNIBEE7B8D.CommonTool;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.net.Proxy;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;

/**
 * Created by sdtz on 2017/8/4.
 */
public class OkHttpUtil {
    private static OkHttpClient client;
    //超时时间
    public static final int TIMEOUT=20;

    //json请求
    public static final MediaType JSON = MediaType
            .parse("application/json; charset=utf-8");

    private static Handler handler = new Handler(Looper.getMainLooper());

    public static String token = "";
    public OkHttpUtil() {
        this.init();
    }
    public OkHttpUtil(String token){
        this.initToken(token);
    }

    private void init() {
        client=new OkHttpClient();


        //设置超时
        client.newBuilder().connectTimeout(TIMEOUT, TimeUnit.SECONDS).
                writeTimeout(TIMEOUT, TimeUnit.SECONDS).readTimeout(TIMEOUT, TimeUnit.SECONDS)
                .proxy(Proxy.NO_PROXY)
                .build();
    }
    private void initToken(String token) {
        this.token = token;
        client=new OkHttpClient();
        //设置超时
        client.newBuilder().connectTimeout(TIMEOUT, TimeUnit.SECONDS).
                writeTimeout(TIMEOUT, TimeUnit.SECONDS).readTimeout(TIMEOUT, TimeUnit.SECONDS)
                .proxy(Proxy.NO_PROXY)
                .build();
    }

    /**
     * post请求  json数据为body
     *
     */
    public void postJson(String url, String json, final HttpCallBack callBack){
        RequestBody body = RequestBody.create(JSON,json);
        final Request request = new Request.Builder().url(url).addHeader("X-Access-Token",token).post(body).build();

        OnStart(callBack);

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OnError(callBack, e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    onSuccess(callBack, response.body().string());
                } else {
                    OnError(callBack, response.message());
                }
            }
        });
    }
    /**
     * post请求  map是body
     *
     * @param url
     * @param map
     * @param callBack
     */
    public void postMap(String url, Map<String, String> map, final HttpCallBack callBack){
        FormBody.Builder builder=new FormBody.Builder();

        //遍历map
        if(map!=null){
            for (Map.Entry<String, String> entry : map.entrySet()){
                builder.add(entry.getKey(), entry.getValue().toString());
            }
        }
        RequestBody body = builder.build();
        Request request = new Request.Builder().url(url).addHeader("X-Access-Token",token).post(body).build();
        OnStart(callBack);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OnError(callBack,e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    onSuccess(callBack,response.body().string());
                }else{
                    OnError(callBack, response.message());
                }
            }
        });
    }
    /**
     * post请求  map是body
     *
     * @param url
     * @param map
     * @param callBack
     */
    public void postMapInteger(String url, Map<String, Integer> map, final HttpCallBack callBack){
        FormBody.Builder builder=new FormBody.Builder();

        //遍历map
        if(map!=null){
            for (Map.Entry<String, Integer> entry : map.entrySet()){
                builder.add(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        RequestBody body = builder.build();
        Request request = new Request.Builder().url(url).post(body).build();
        OnStart(callBack);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OnError(callBack,e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    onSuccess(callBack,response.body().string());
                }else{
                    OnError(callBack, response.message());
                }
            }
        });
    }




 /*   /*//**
     * 上传文件
     * @param url 连接地址
     * @param callBack 回调
     *//**//**/
    public static void upLoadFile(String url, Map<String, String> map, HashMap<String, File> fileHashMap, final HttpCallBack callBack) {

        try {
            FormBody.Builder builder=new FormBody.Builder();

            //遍历map
            if(map!=null){
                for (Map.Entry<String, String> entry : map.entrySet()){
                    builder.add(entry.getKey(), entry.getValue().toString());
                }
            }
            RequestBody body = builder.build();
            Request request = new Request.Builder().url(url).post(body).build();
            OnStart(callBack);
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    OnError(callBack,e.getMessage());
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if(response.isSuccessful()){
                        onSuccess(callBack,response.body().string());
                    }else{
                        OnError(callBack, response.message());
                    }
                }
            });
        } catch (Exception e) {
            Log.d("==", e.toString());
        }
    }
    /**
     * get 请求
     *
     * @param url
     * @param callBack
     */
    public void getJson(String url, final HttpCallBack callBack){
        Request request = new Request.Builder().url(url).addHeader("X-Access-Token",token).build();

        OnStart(callBack);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OnError(callBack,e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    onSuccess(callBack,response.body().string());
                }else{
                    OnError(callBack,response.message());
                }
            }
        });
    }

    //上传文件
    public void postFile(String url, Map<String, String> params, List<File> files, final  HttpCallBack callBack){
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);

        //遍历map中所有参数到builder
        if (params != null){
            for (String key : params.keySet()) {
                multipartBodyBuilder.addFormDataPart(key, params.get(key));
            }
        }
        //遍历map中所有参数到builder
        if (files.size() != 0){
            for(int i=0;i<files.size();i++){
                multipartBodyBuilder.addFormDataPart("image["+i+"]", files.get(i).getName(), RequestBody.create(MediaType.parse("image/*"), files.get(i)));
            }
        }
        Request.Builder RequestBuilder = new Request.Builder();
        RequestBuilder.url(url);// 添加URL地址
        if(multipartBodyBuilder!= null){
            //构建请求体
            RequestBody requestBody = multipartBodyBuilder.build();
            RequestBuilder.post(requestBody);
        }

        Request request = RequestBuilder.build();




        OnStart(callBack);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OnError(callBack,e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    onSuccess(callBack,response.body().string());
                }else{
                    OnError(callBack,response.message());
                }
            }
        });
    }


    //上传文件
    public void postUserFile(String url, Map<String, String> params, List<File> files, final  HttpCallBack callBack){
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);

        //遍历map中所有参数到builder
        if (params != null){
            for (String key : params.keySet()) {
                multipartBodyBuilder.addFormDataPart(key, params.get(key));
            }
        }
        //遍历map中所有参数到builder
        if (files.size() != 0){
            for(int i=0;i<files.size();i++){
                multipartBodyBuilder.addFormDataPart("avatar", files.get(i).getName(), RequestBody.create(MediaType.parse("image/*"), files.get(i)));
            }
        }
        Request.Builder RequestBuilder = new Request.Builder();
        RequestBuilder.url(url);// 添加URL地址
        if(multipartBodyBuilder!= null){
            //构建请求体
            Log.d("==",multipartBodyBuilder.toString());
            RequestBody requestBody = multipartBodyBuilder.build();
            RequestBuilder.post(requestBody);
        }

        Request request = RequestBuilder.build();




        OnStart(callBack);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OnError(callBack,e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    onSuccess(callBack,response.body().string());
                }else{
                    OnError(callBack,response.message());
                }
            }
        });
    }
    public void updateVideo(String reqUrl, List<File> videos, final HttpCallBack callBack){
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);
        //遍历paths中所有图片绝对路径到builder，并约定key如“upload”作为后台接受多张图片的key
       if (videos.size() != 0){
            for(int i=0;i<videos.size();i++){
                multipartBodyBuilder.addFormDataPart("video", videos.get(i).getName(), RequestBody.create(MediaType.parse("video*//*"), videos.get(i)));
            }
        }

        //构建请求体
        RequestBody requestBody = multipartBodyBuilder.build();

        Request.Builder RequestBuilder = new Request.Builder();
        RequestBuilder.url(reqUrl);// 添加URL地址
        RequestBuilder.post(requestBody);
        Request request = RequestBuilder.build();
        OnStart(callBack);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OnError(callBack,e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    onSuccess(callBack,response.body().string());
                }else{
                    OnError(callBack,response.message());
                }
            }
        });
    }

    //上传多张图片
    public void postMoreImage(String reqUrl, Map<String, String> params, List<File> files, List<File> videos, final  HttpCallBack callBack){
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);
        //遍历map中所有参数到builder
        if (params != null){
            for (String key : params.keySet()) {
                multipartBodyBuilder.addFormDataPart(key, params.get(key));
            }
        }
        //遍历paths中所有图片绝对路径到builder，并约定key如“upload”作为后台接受多张图片的key
        if (files.size() != 0){
            for(int i=0;i<files.size();i++){
                multipartBodyBuilder.addFormDataPart("photos["+i+"]", files.get(i).getName(), RequestBody.create(MediaType.parse("image/*"), files.get(i)));
            }
        }
        if (videos.size() != 0){
            for(int i=0;i<videos.size();i++){
                multipartBodyBuilder.addFormDataPart("videofile", videos.get(i).getName(), RequestBody.create(MediaType.parse("video/*"), videos.get(i)));
            }
        }
        //构建请求体
        RequestBody requestBody = multipartBodyBuilder.build();

        Request.Builder RequestBuilder = new Request.Builder();
        RequestBuilder.url(reqUrl);// 添加URL地址
        RequestBuilder.post(requestBody);
        final Request request = RequestBuilder.build();
        OnStart(callBack);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OnError(callBack,e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    onSuccess(callBack,response.body().string());
                }else{
                    OnError(callBack,response.message());
                }
            }

        });

    }



    public static void OnStart(HttpCallBack callBack){
        if(callBack!=null){
            callBack.onstart();
        }
    }
    public static void onSuccess(final HttpCallBack callBack, final String data){
        if(callBack!=null){
            handler.post(new Runnable() {
                @Override
                public void run() {//在主线程操作
                    try {
                        callBack.onSusscess(data);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    public static void OnError(final HttpCallBack callBack, final String msg){
        if(callBack!=null){
            handler.post(new Runnable() {
                @Override
                public void run() {
                    callBack.onError(msg);
                }
            });
        }
    }
    public static abstract class HttpCallBack{
        //开始
        public void onstart(){};
        //成功回调
        public abstract void onSusscess(String data) throws JSONException, ParseException;
        //失败
        public void onError(String meg){};

        public void onSuccessMsg(String data){}

    }


    /**
     * @param reqUrl
     * @param params
     * @param files
     * @param videos
     * @param callBack
     */
    public void UploadFiles(String reqUrl, Map<String, String> params, List<File> files, List<File> videos, final  HttpCallBack callBack){
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);
        //遍历map中所有参数到builder
        if (params != null){
            for (String key : params.keySet()) {
                multipartBodyBuilder.addFormDataPart(key, params.get(key));
            }
        }
        //遍历paths中所有图片绝对路径到builder，并约定key如“upload”作为后台接受多张图片的key
        if (files.size() != 0){
            for(int i=0;i<files.size();i++){
                multipartBodyBuilder.addFormDataPart("photos["+i+"]", files.get(i).getName(), RequestBody.create(MediaType.parse("image/*"), files.get(i)));
            }
        }
        if (videos.size() != 0){
            for(int i=0;i<videos.size();i++){
                multipartBodyBuilder.addFormDataPart("videofile", videos.get(i).getName(), RequestBody.create(MediaType.parse("video/*"), videos.get(i)));
            }
        }
        //构建请求体
        RequestBody requestBody = multipartBodyBuilder.build();

        Request.Builder RequestBuilder = new Request.Builder();
        RequestBuilder.url(reqUrl);// 添加URL地址
        RequestBuilder.post(requestBody);
        final Request request = RequestBuilder.build();
        OnStart(callBack);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OnError(callBack,e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    onSuccess(callBack,response.body().string());
                }else{
                    OnError(callBack,response.message());
                }
            }

        });

    }


    /**
     * 传输进度监听器
     */
    public interface ProgressListener {
        void onProgress(long totalSize, long currSize, boolean done, int id);
    }

    /**
     * 继承RequestBody,实现上传的进度监听
     */
    private class ProgressRequestBody extends RequestBody {
        MediaType contentType;
        File file;
        ProgressListener listener;
        int id;

        /**
         * 构造函数
         *
         * @param id          一次可以上传多个文件,id表示本文件在这一批文件当中的编号
         * @param contentType MIME类型
         * @param file        要上传的文件
         * @param listener    传输进度监听器
         */
        public ProgressRequestBody(int id, MediaType contentType, File file, ProgressListener listener) {
            this.id = id;
            this.contentType = contentType;
            this.file = file;
            this.listener = listener;
        }


        @Override
        public MediaType contentType() {
            return contentType;
        }

        @Override
        public long contentLength() throws IOException {
            return file.length();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Source source;
            long len;//记录本次读了多少数据
            long currSize = 0;//记录目前一共读了多少数据
            long totalSize = contentLength();//一共有多少数据

            try {
                source = Okio.source(file);
                Buffer buffer = new Buffer();

                while ((len = source.read(buffer, 2048)) != -1) {
                    sink.write(buffer, len);
                    sink.flush();
                    currSize += len;

                    //回调,进度监听
                    listener.onProgress(totalSize, currSize, totalSize == currSize, id);
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
